package com.easou.ps.main;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TServerSocket;

import com.easou.ps.common.servicehandle.GBKCompactProtocol;
import com.easou.ps.webmaster.MasterService;
import com.easou.ps.webmaster.SearchRequest;
import com.easou.ps.webmaster.SearchResponse;

public class MiscServer {
	public static final Logger TIME_LOG = Logger.getLogger("cost_time");
	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			usage(args);
			System.exit(-1);
		}

		int searchPort = -1;
		try {
			searchPort = Integer.parseInt(args[0]);
		} catch (Exception e) {
			usage(args);
			System.exit(-1);
		}

		if (searchPort < 1) {
			usage(args);
			System.exit(-1);
		} else {
			Initializer.exec();
			startSearchServer(searchPort);
		}
		
	}
	
	private static void usage(String[] args) {
		System.out.println("master args is error:" + java.util.Arrays.toString(args));
		System.out.println("MasterServer searchPort");
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static void startSearchServer(final int port) throws Exception {
		final MasterService.Processor processor = new MasterService.Processor(
			new MasterService.Iface() {
				@Override
				public SearchResponse search(SearchRequest req)
						throws TException {
					try {
					SearchResponse response = null;
					long start = System.currentTimeMillis();
					MiscSearcher searcher  = new MiscSearcher();
					response = searcher.toSearch(req);
					long cost = System.currentTimeMillis() - start;
					System.out.println("cost:"+cost);			
					return response;
				}
					catch(Exception e) {
						e.printStackTrace();
						throw new TException(e);
					}
				}
			});
		
		final TServerSocket socket = new TServerSocket(port, 60000);
		TThreadPoolServer.Args arg = new TThreadPoolServer.Args(socket)
				.maxWorkerThreads(120).processor(processor)
				.transportFactory(new TFramedTransport.Factory())
				.protocolFactory(new GBKCompactProtocol.Factory());

		TServer server = new TThreadPoolServer(arg);
		server.serve();
	}
}
